import {login, logout, getInfo} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter, constantRoutes} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login  用户登录
  login({commit}, userInfo) {
    const {username, password} = userInfo
    return new Promise((resolve, reject) => {
      login({username: username.trim(), password: password}).then(response => {
        if (response.code) {
          const {token} = response
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        } else {
          reject()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info  拉取用户信息
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {data} = response

        if (!data) {
          return reject('验证失败，请重新登录.')
        }


        console.log(response,constantRoutes,"11111111") // msg里面就是返回的权限

        // var resRouter = filterAsyncRoutes(constantRoutes, response)
        // console.log(resRouter, 'resRouter')
        const {Username, avatar} = data
        commit('SET_NAME', Username)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // 必须先删除令牌
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

/**
 * 递归过滤AsyncRoutes路由表
 * @param routes asyncRoutes   待过滤路由表,首次传入的就是AsyncRoutes
 * @param roles   用户佣有角色
 */
// 生成可访问路由
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    // 复制一份
    const tmp = { ...route }
    // 判断当前路由是否可以访问
    if (tmp.children) { // 权限部分的优化
      tmp.children = filterAsyncRoutes(tmp.children, roles)
      if (tmp.children && tmp.children.length > 0) {
        res.push(tmp)
      }
    } else {
      if (roles.some(role => route.path.includes(role.Path))) {
        res.push(tmp)
      }
    }
  })
  return res
}
